import { createSlice } from "@reduxjs/toolkit";

const settingStore = createSlice({
  name: "setting",
  // 初始化state
  initialState: {
    collapsed: false,
    tagList: [
      {
        path: "/",
        name: "home",
        label: "首页",
      },
    ],
    currentMenu: {}
  },
  // 修改状态的方法
  reducers: {
    collapsedChange(state) {
      state.collapsed = !state.collapsed;
    },
    addTagList: (state, { payload }) => {
      console.log('payload', payload)
      if (payload.name != "home") {
         state.currentMenu = payload
         // 先判断state.tagList中是否已经有该tag
         const result = state.tagList.findIndex(item => item.name == payload.name)
         if (result === -1) {
            state.tagList.push(payload)
         }
      } else if(payload.name === 'home' && state.tagList.length == 1) {
         state.currentMenu = {}
      }
    },
    closeTag: (state, { payload }) => {
      const index = state.tagList.findIndex(item => item.name == payload.name)
      state.tagList.splice(index, 1)
    },
    setCurrentMenu: (state, { payload }) => {
      if (payload.name === 'home') {
        state.currentMenu = {}
      } else {
        state.currentMenu = payload
      }
    },
  },
});
// 以按需导出的方式导出actionCreater
export const { collapsedChange, addTagList, closeTag, setCurrentMenu } = settingStore.actions;
// 以默认导出的方式导出reducer
export default settingStore.reducer;
